﻿using FreeSql;
using Kalman;
using Kalman.Jwt;
using Kalman.Security;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace AdminUI
{
    public static class Extensions
    {
        #region FreeSql数据库配置
        public static void ConfigureDatabase(this IServiceCollection services)
        {
            var dbType = DataType.MySql;
            var css = AppConfig.Instance.GetConnectionStringSettings();
            //switch (css.ProviderName)
            //{
            //    case "MySql.Data.MySqlClient":
            //        dbType = DataType.MySql;
            //        break;
            //    default:
            //        break;
            //}

            var sqlBuilder = new FreeSqlBuilder()
                    .UseConnectionString(dbType, css.ConnectionString)
                    .UseAutoSyncStructure(false)
                    .UseLazyLoading(false)
                    .UseNoneCommandParameter(true);//不使用命令参数化执行，针对 Insert/Update，也可临时使用 IInsert/IUpdate.NoneParameter()


            //监听所有命令
            sqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) =>
            {
                //Console.WriteLine($"{cmd.CommandText}\n{traceLog}\r\n");
                Console.WriteLine($"{cmd.CommandText}\r\n");
            });

            var freeSql = sqlBuilder.Build();
            services.AddSingleton(freeSql);

            //监听Curd操作
            freeSql.Aop.CurdBefore += (s, e) =>
            {
                Console.WriteLine($"{e.Sql}\r\n");
            };
        }
        #endregion

        /// <summary>
        /// 获取请求客户端的IP地址
        /// </summary>
        public static string GetRequestIP(this HttpContext context)
        {
            var ip = string.Empty;
            var host = context.Request.Host;

            if (host.HasValue)
            {
                ip = host.Host;
                if (ip == "localhost")
                {
                    ip = "127.0.0.1";
                }
            }

            return ip;
        }
    }
}
